package com.gxgeek.springweb.model;

import org.apache.commons.io.IOUtils;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.*;

/**
 * @author gaoxing
 * @create 2018-08-30 下午2:10
 */
public class BaseRequestWrapper extends HttpServletRequestWrapper {
    private byte[] rawData;
    private HttpServletRequest request;
    private BaseRequestWrapper.ResettableServletInputStream servletStream;

    /**
     * Constructs a request object wrapping the given request.
     *
     * @param request The request to wrap
     * @throws IllegalArgumentException if the request is null
     */
    public BaseRequestWrapper(HttpServletRequest request) {
        super(request);
        this.request = request;
        this.servletStream = new BaseRequestWrapper.ResettableServletInputStream();
    }
    private class ResettableServletInputStream extends ServletInputStream {
        private InputStream stream;

        private ResettableServletInputStream() {
        }

        @Override
        public int read() throws IOException {
            return this.stream.read();
        }

        @Override
        public boolean isFinished() {
            return false;
        }

        @Override
        public boolean isReady() {
            return false;
        }

        @Override
        public void setReadListener(ReadListener readListener) {
        }
    }



    @Override
    public ServletInputStream getInputStream() throws IOException {
        if (this.rawData == null) {
            this.rawData = IOUtils.toByteArray(this.request.getInputStream());
            this.servletStream.stream = new ByteArrayInputStream(this.rawData);
        } else {
            this.resetInputStream();
        }

        return this.servletStream;
    }
    public void resetInputStream() {
        IOUtils.closeQuietly(this.servletStream.stream);
        this.servletStream.stream = new ByteArrayInputStream(this.rawData);
    }
    @Override
    public BufferedReader getReader() throws IOException {
        if (this.rawData == null) {
            this.rawData = IOUtils.toByteArray(this.request.getInputStream());
            this.servletStream.stream = new ByteArrayInputStream(this.rawData);
        } else {
            this.resetInputStream();
        }

        return new BufferedReader(new InputStreamReader(this.servletStream));
    }




}
